<template>
  <div class="send-display-container">
    <div class="filter-container">
      <div class="label">真实姓名：</div>
      <div class="input-container">
        <a-input v-model="form.realName"/>
      </div>
      <div class="label">手机号码：</div>
      <div class="input-container">
        <a-input v-model="form.mobile"/>
      </div>
      <div class="label">用户状态：</div>
      <div class="input-container">
        <a-select style="width: 200px" v-model="form.valid" allowClear placeholder="请选择">
          <a-select-option value="1">
            正常
          </a-select-option>
          <a-select-option value="0">
            冻结
          </a-select-option>
        </a-select>
      </div>
      <a-button type="primary" class="btn" @click="initList">查询</a-button>
      <a-button class="btn" @click="resetForm">重置</a-button>
    </div>
    <div style="margin-bottom: 30px;">
      <a-button type="primary" class="btn" @click="showModal">新增</a-button>
      <a-modal
        :title="title"
        :visible="addVisible"
        :confirm-loading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <div style="margin-top: 24px;">
          <div class="test">
            <a-form-model
              style="width: 50%;min-width: 930px"
              ref="ruleAddForm"
              :model="addForm"
              :rules="addRules"
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
            >
              <a-row>
                <a-col :span="12">
                  <a-form-model-item ref="userName" label="用户账号" prop="userName">
                    <a-input
                      v-model="addForm.userName"
                      @blur="() => { $refs.userName.onFieldBlur() }"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item ref="realName" label="真实姓名" prop="realName">
                    <a-input
                      v-model="addForm.realName"
                      @blur="() => { $refs.realName.onFieldBlur() }"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item label="性别" prop="sex">
                    <a-select v-model="addForm.sex" placeholder="请选择">
                      <a-select-option value="1">
                        男
                      </a-select-option>
                      <a-select-option value="0">
                        女
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item ref="title" label="职位" prop="title">
                    <a-input
                      v-model="addForm.title"
                      @blur="() => { $refs.title.onFieldBlur() }"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item ref="isValid" label="状态" prop="isValid">
                    <a-select v-model="addForm.isValid" placeholder="请选择">
                      <a-select-option value="1">
                        正常
                      </a-select-option>
                      <a-select-option value="0">
                        冻结
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item ref="mobile" label="手机号码" prop="mobile">
                    <a-input
                      v-model="addForm.mobile"
                      @blur="() => { $refs.mobile.onFieldBlur() }"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item ref="roleIdData" label="角色授权" prop="roleIdData">
                    <a-select
                      style="width: 100%"
                      mode="multiple"
                      v-model="roleIdData"
                      :allowClear="true"
                    >
                      <a-select-option v-for="(action, index) in roleList" :key="index" :value="action.roleId">{{
                        action.roleName }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item ref="groupIdData" label="机构授权" prop="groupIdData">
                    <a-select
                      mode="multiple"
                      style="width: 100%"
                      placeholder="请选择机构"
                      @change="handleChange"
                      :maxTagCount="1"
                      :value="groupIdData"
                    >
                      <div slot="dropdownRender" slot-scope="menu">
                        <v-nodes :vnodes="menu" />
                        <a-divider style="margin: 4px 0;" />
                        <div style="padding: 4px 8px; cursor: pointer;" @mousedown="e => e.preventDefault()">
                          <a-button type="link" @click="selectAll">全选</a-button>
                          <a-button type="link" @click="clearAll">清空</a-button>
                        </div>
                      </div>
                      <a-select-option v-for="i in groupTree" :key="i.groupId">
                        {{ i.groupName }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="24">
                  <a-form-model-item :labelCol="{span: 2, offset: 0}" ref="bz" label="备注" prop="bz">
                    <div style="width: 135.6%;">
                      <a-textarea
                        v-model="addForm.bz"
                        placeholder=""
                        :auto-size="{ minRows: 3, maxRows: 10 }"
                      />
                    </div>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
          </div>
        </div>
      </a-modal>
    </div>
    <a-table
      :columns="columns"
      :data-source="data"
      bordered
      :loading="loading"
      :pagination="pagination"
      @change="tableChange"
      :rowKey="(record,index)=>{return index}"
    >
      <a slot="b" slot-scope="text" href="https://www.google.com">{{ text }}</a>
      <span slot="action" slot-scope="text, record">
        <a href="javascript:" @click="updateShowModal( text, record.userId )">编辑</a>
        <a-divider type="vertical"/>
        <a-dropdown>
          <a class="ant-dropdown-link">
            更多 <a-icon type="down"/>
          </a>
          <a-menu slot="overlay">
            <a-menu-item>
              <a href="javascript:" @click="showDrawer( text, record.userId )">详情</a>
              <a-drawer
                width="30%"
                title="用户信息"
                placement="right"
                :visible="visible"
                :after-visible-change="afterVisibleChange"
                @close="onClose"
              >
                <div style="margin-top: 24px">
                  <a-form-model
                    ref="ruleForm"
                    :model="DetailsForm"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol"
                  >
                    <a-form-model-item ref="userName" label="用户账号" prop="userName">
                      <a-input
                        disabled
                        v-model="DetailsForm.userName"
                        @blur="() => { $refs.userName.onFieldBlur() }"></a-input>
                    </a-form-model-item>
                    <a-form-model-item ref="realName" label="真实姓名" prop="realName">
                      <a-input
                        disabled
                        v-model="DetailsForm.realName"
                        @blur="() => { $refs.realName.onFieldBlur() }"></a-input>
                    </a-form-model-item>
                    <a-form-model-item label="性别" prop="sex">
                      <a-select v-model="DetailsForm.sex" disabled placeholder="请选择">
                        <a-select-option value="1">
                          男
                        </a-select-option>
                        <a-select-option value="0">
                          女
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                    <a-form-model-item ref="title" label="职位" prop="title">
                      <a-input
                        disabled
                        v-model="DetailsForm.title"
                        @blur="() => { $refs.title.onFieldBlur() }"></a-input>
                    </a-form-model-item>
                    <a-form-model-item ref="isValid" label="状态" prop="isValid">
                      <a-select v-model="DetailsForm.isValid" disabled placeholder="请选择">
                        <a-select-option value="1">
                          正常
                        </a-select-option>
                        <a-select-option value="0">
                          冻结
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                    <a-form-model-item ref="mobile" label="手机号码" prop="mobile">
                      <a-input
                        disabled
                        v-model="DetailsForm.mobile"
                        @blur="() => { $refs.mobile.onFieldBlur() }"></a-input>
                    </a-form-model-item>
                    <a-form-model-item ref="roleIdData" label="角色信息" prop="roleIdData">
                      <a-select
                        disabled
                        style="width: 100%"
                        mode="multiple"
                        v-model="DetailsForm.roleIdData"
                        :allowClear="true"
                      >
                        <a-select-option v-for="(action, index) in roleList" :key="index" :value="action.roleId">{{ action.roleName }}</a-select-option>
                      </a-select>
                    </a-form-model-item>
                    <a-form-model-item ref="groupIdData" label="机构信息" prop="groupIdData">
                      <a-select
                        disabled
                        mode="multiple"
                        style="width: 100%"
                        placeholder="请选择机构"
                        @change="detailsHandleChange"
                        :value="DetailsForm.groupIdData"
                      >
                        <a-select-option v-for="i in groupTree" :key="i.groupId">
                          {{ i.groupName }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                    <a-form-model-item ref="bz" label="备注" prop="bz">
                      <a-textarea
                        disabled
                        v-model="DetailsForm.bz"
                        placeholder=""
                        :auto-size="{ minRows: 3, maxRows: 10 }"
                      />
                    </a-form-model-item>
                  </a-form-model>
                </div>
                <div
                  :style="{
                    position: 'absolute',
                    right: 0,
                    bottom: 0,
                    width: '100%',
                    borderTop: '1px solid #e9e9e9',
                    padding: '10px 16px',
                    background: '#fff',
                    textAlign: 'right',
                    zIndex: 1,
                  }"
                >
                  <a-button :style="{ marginRight: '8px' }" @click="onClose">
                    关闭
                  </a-button>
                </div>
              </a-drawer>
            </a-menu-item>
            <a-menu-item>
              <a-popconfirm
                title="是否删除？"
                ok-text="是"
                cancel-text="否"
                @confirm="confirmDel( text, record.userId )"
                @cancel="cancelDel"
              >
                <a href="#">删除</a>
              </a-popconfirm>
            </a-menu-item>
            <a-menu-item>
              <a-popconfirm
                title="是否冻结？"
                ok-text="是"
                cancel-text="否"
                @confirm="confirmUpdate( text, record.userId )"
                @cancel="cancelUpdate"
              >
                <a href="#">冻结</a>
              </a-popconfirm>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </span>
    </a-table>
  </div>
</template>

<script>
  import {
    getUserList,
    getUserInfo,
    deleteUserInfo,
    updateUserInfo,
    addUserInfo,
    getAllRoleList,
    getTreeData
  } from '@/api/rbac'
  import { TreeSelect } from 'ant-design-vue'

  const columns = [
    {
      title: '用户账号',
      dataIndex: 'userName',
      key: 'userName',
      align: 'center'
    },
    {
      title: '真实姓名',
      dataIndex: 'realName',
      key: 'realName',
      align: 'center'

    },
    {
      title: '状态',
      dataIndex: 'valid',
      key: 'valid',
      align: 'center'

    },
    {
      title: '手机号码',
      dataIndex: 'mobile',
      key: 'mobile',
      align: 'center'

    },
    {
      title: '最后登录时间',
      dataIndex: 'lastLoginTime',
      key: 'lastLoginTime',
      align: 'center'

    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      scopedSlots: { customRender: 'action' }
    }

  ]
  const SHOW_PARENT = TreeSelect.SHOW_PARENT

  export default {
    name: 'User',
    components: {
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes
      }
    },
    data () {
      return {
        roleIdData: [],
        groupIdData: [],
        data: [],
        columns,
        form: {
          realName: null,
          mobile: null,
          valid: '1'
        },
        title: '',
        DetailsForm: {
          userName: null,
          realName: null,
          sex: null,
          title: null,
          headImg: null,
          isValid: null,
          mobile: null,
          bz: null,
          roleIds: '',
          groupIds: '',
          roleIdData: [],
          groupIdData: []
        },
        addForm: {
          userId: '',
          userName: null,
          realName: null,
          sex: null,
          title: null,
          headImg: null,
          isValid: '1',
          mobile: null,
          bz: null,
          roleIds: '',
          groupIds: ''
        },
        SHOW_PARENT,
        roleList: [],
        groupTree: [],
        expandedKeys: [],
        addRules: {
          userName: [
            { required: true, message: '请输入用户账号!', trigger: 'blur' }
          ],
          realName: [
            { required: true, message: '请输入真实姓名!', trigger: 'blur' }
          ],
          sex: [
            { required: true, message: '请选择性别!', trigger: 'blur' }
          ],
          title: [
            { required: true, message: '请输入职位!', trigger: 'blur' }
          ],
          headImg: [
            { required: true, message: '请输入头像路径!', trigger: 'blur' }
          ],
          isValid: [
            { required: true, message: '请选择状态!', trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '请输入手机号!', trigger: 'blur' }
          ],
          roleIds: [
            { required: true, message: '请选择角色信息!', trigger: 'blur' }
          ],
          groupIds: [
            { required: true, message: '请选择机构信息!', trigger: 'blur' }
          ]
        },
        visible: false,
        flag: false,
        addVisible: false,
        confirmLoading: false,
        loading: false,
        selectedRowKeys: [],
        autoExpandParent: true,
        selectedKeys: [],
        replaceFields: {
          children: 'children',
          title: 'groupName',
          value: 'groupId',
          key: 'groupId'
        },
        wrapperCol: { span: 14 },
        labelCol: { span: 4 },
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `显示第${range[0]}至${range[1]}项结果，共${total}项`
        }
      }
    },
    mounted () {
      this.initList()
    },
    methods: {
      initList () {
        this.pagination.current = 1
        this.onQuery()
        this.queryRoleList()
        this.onTree()
      },
      onTree () {
        getTreeData().then(res => {
          this.groupTree = res.retObj[0].children
          this.expandedKeys = []
        })
      },
      onChangeDate (date, dateString) {
        console.log(date, dateString)
      },
      // 分页，sort变化
      tableChange (pagination) {
        this.pagination = pagination
        this.onQuery()
      },
      afterVisibleChange (val) {
        console.log('visible', val)
      },
      showDrawer (text, userId) {
        const that = this
        this.visible = true
        getUserInfo({ 'userId': userId }).then(res => {
          this.DetailsForm = res.retObj.userInfo
          this.DetailsForm.groupIdData = []
          this.DetailsForm.roleIdData = []
          console.log(res.retObj)
          res.retObj.groupList.forEach(x => {
            that.DetailsForm.groupIdData.push(x.groupId)
          })
          res.retObj.roleList.forEach(x => {
            that.DetailsForm.roleIdData.push(x.roleId)
          })
        })
      },
      showUpdateDrawer (text, userId) {
        const that = this
        this.visible = true
        getUserInfo({ 'userId': userId }).then(res => {
          this.DetailsForm = res.retObj.userInfo
          this.DetailsForm.groupIdData = []
          this.DetailsForm.roleIdData = []
          console.log(res.retObj)
          res.retObj.groupList.forEach(x => {
            that.DetailsForm.groupIdData.push(x.groupId)
          })
          res.retObj.roleList.forEach(x => {
            that.DetailsForm.roleIdData.push(x.roleId)
          })
        })
      },
      handleChange (value) {
        this.groupIdData = value
      },
      detailsHandleChange (value) {
        this.DetailsForm.groupIdData = value
      },
      queryRoleList () {
        getAllRoleList({}).then(res => {
          this.roleList = res.retObj
        })
      },
      onQuery () {
        this.loading = true
        const params = {
          realName: this.form.realName === '' ? null : this.form.realName,
          mobile: this.form.mobile === '' ? null : this.form.mobile,
          valid: this.form.valid === '' ? null : this.form.valid,
          currentPage: this.pagination.current.toString(),
          pageSize: this.pagination.pageSize.toString()
        }
        getUserList(params).then(res => {
          this.loading = false
          if (res.retCode === 0) {
            this.data = res.retObj.data
            this.pagination.total = parseInt(res.retObj.count)
          }
        }).catch(error => {
          this.loading = false
          console.log(error)
        })
      },
      onDel (text, userId) {
        deleteUserInfo({ 'userId': userId }).then(res => {
          if (res.retCode === 0) {
            this.$notification['success']({
              message: '提示',
              description: '删除成功！',
              duration: 8
            })
            this.onQuery()
          } else {
            this.$notification['error']({
              message: '提示',
              description: res.retMsg,
              duration: 8
            })
          }
        })
      },
      onFreeze (text, userId) {
        updateUserInfo({ 'userId': userId, 'isValid': '0' }).then(res => {
          if (res.retCode === 0) {
            this.$notification['success']({
              message: '提示',
              description: '已冻结该用户！',
              duration: 8
            })
            this.onQuery()
          } else {
            this.$notification['error']({
              message: '提示',
              description: res.retMsg,
              duration: 8
            })
          }
        })
      },
      onUpdate () {
        this.$refs.ruleAddForm.validate(valid => {
          if (valid) {
            var groupIds = ''
            this.groupIdData.forEach(x => {
              groupIds += x + ','
            })
            groupIds = groupIds.substring(0, groupIds.length - 1)
            const params = {
              userId: this.addForm.userId,
              userName: this.addForm.userName,
              realName: this.addForm.realName,
              sex: this.addForm.sex,
              title: this.addForm.title,
              headImg: this.addForm.headImg,
              isValid: this.addForm.isValid,
              mobile: this.addForm.mobile,
              bz: this.addForm.bz,
              roleIds: this.roleIdData.toLocaleString(),
              groupIds: groupIds
            }
            console.log('params', params)
            updateUserInfo(params).then(res => {
              if (res.retCode === 0) {
                this.$notification['success']({
                  message: '提示',
                  description: '用户信息修改成功！',
                  duration: 8
                })
                this.onQuery()
                this.addVisible = false
              } else {
                this.$notification['error']({
                  message: '提示',
                  description: res.retMsg,
                  duration: 8
                })
              }
            })
          } else {
            return false
          }
        })
      },
      onSave () {
        this.$refs.ruleAddForm.validate(valid => {
          if (valid) {
            var groupIds = ''
            console.log(this.groupIdData)
            this.groupIdData.forEach(x => {
              groupIds += x + ','
            })
            groupIds = groupIds.substring(0, groupIds.length - 1)
            console.log(groupIds)
            const params = {
              userName: this.addForm.userName,
              realName: this.addForm.realName,
              sex: this.addForm.sex,
              title: this.addForm.title,
              headImg: this.addForm.headImg,
              isValid: this.addForm.isValid,
              mobile: this.addForm.mobile,
              bz: this.addForm.bz,
              roleIds: this.roleIdData.toLocaleString(),
              groupIds: groupIds
            }
            console.log('params', params)
            addUserInfo(params).then(res => {
              if (res.retCode === 0) {
                this.$notification['success']({
                  message: '提示',
                  description: '用户信息保存成功！',
                  duration: 8
                })
                this.onQuery()
                this.addVisible = false
              } else {
                this.$notification['error']({
                  message: '提示',
                  description: res.retMsg,
                  duration: 8
                })
              }
            })
          } else {
            return false
          }
        })
      },
      onExpand (expandedKeys) {
        console.log('onExpand', expandedKeys)
        this.expandedKeys = expandedKeys
        this.autoExpandParent = false
      },
      onSelect (selectedKeys, info) {
        console.log('onSelect', info)
        this.selectedKeys = selectedKeys
      },
      showModal () {
        this.addVisible = true
        this.title = '新增用户'
        this.groupIdData = []
        this.roleIdData = []
        this.addForm = {
            userId: '',
            userName: null,
            realName: null,
            sex: null,
            title: null,
            headImg: null,
            isValid: '1',
            mobile: null,
            bz: null,
            roleIds: '',
            groupIds: ''
        }
        this.flag = true
      },
      updateShowModal (text, userId) {
        this.addVisible = true
        this.title = '编辑用户'
        this.flag = false
        getUserInfo({ 'userId': userId }).then(res => {
          this.addForm = res.retObj.userInfo
          this.groupIdData = []
          this.roleIdData = []
          console.log(res.retObj)
          this.addForm.userId = userId
          const cache = []
          res.retObj.groupList.forEach(x => {
            cache.push(x.groupId)
          })
          this.groupIdData = cache
          const roleCache = []
          res.retObj.roleList.forEach(x => {
            roleCache.push(x.roleId)
          })
          this.roleIdData = roleCache
        })
      },
      confirmDel (text, userId) {
        this.onDel(text, userId)
      },
      cancelDel () {
      },
      confirmUpdate (text, userId) {
        this.onFreeze(text, userId)
      },
      cancelUpdate () {
      },
      selectAll () {
        const arr = [];
        (this.groupTree).forEach(item => {
          arr.push(item.groupId)
        })
        this.groupIdData = arr
      },
      // 清空 -- 清空select绑定的值
      clearAll () {
        this.groupIdData = []
      },
      handleOk () {
        if (this.flag) {
          this.onSave()
        } else {
          this.onUpdate()
        }
      },
      handleCancel () {
        console.log(this.addForm)
        this.addVisible = false
        this.addForm = {}
        this.roleIdData = []
        this.groupIdData = []
      },
      onSelectChange (selectedRowKeys) {
        console.log('selectedRowKeys changed: ', selectedRowKeys)
        this.selectedRowKeys = selectedRowKeys
      },
      resetForm () {
        this.form = {
          realName: null,
          mobile: null,
          valid: '1'
        }
        this.initList()
      },
      onClose () {
        console.log(1)
        this.visible = false
      }
    }
  }
</script>

<style scoped lang="less">
  .send-display-container {
    width: 100%;
    background-color: #ffffff;
    padding: 24px;
  }

  .filter-container {
    display: flex;
    align-items: center;
    padding-bottom: 24px;
    justify-content: left;

    .label {
      padding-right: 20px;
      white-space: nowrap;
    }

    .input-container {
      width: 200px;
      margin-right: 20px
    }

    .btn {
      margin-right: 20px;
    }
  }

  /deep/ .ant-modal-content {
    min-width: 930px;
    margin-left: -35%;
  }
</style>
